import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.SimpleAdapter
import android.widget.Spinner
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class SimpleAdapterActivity : AppCompatActivity() {

    // 0. 数据类
    data class CityData(val icon: Int, val text: String)

    // 1. 定义城市列表
    private val cityList = listOf<CityData>(
        CityData(R.drawable.bj, "北京"),
        CityData(R.drawable.sh, "上海"),
        CityData(R.drawable.gz, "广州"),
        CityData(R.drawable.sz, "深圳"),
        CityData(R.drawable.hz, "杭州"),
        CityData(R.drawable.nj, "南京"),
    )

    // 2. 定义变量接收下拉列表
    private lateinit var spCity: Spinner
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_simple_adapter)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        // 根据id获取元素
        spCity = findViewById(R.id.spinner_icon)

        // 创建适配器
        spCity.adapter = SimpleAdapter(
            this,// 上下文
            // 映射
            cityList.map {
                mapOf("icon" to it.icon, "text666" to it.text)
            },
            R.layout.item_icon,
            arrayOf("icon", "text666"),
            intArrayOf(R.id.icon, R.id.text)
        )

        // 点击 弹窗的时候 输出当前点击的城市名
        spCity.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                val city = cityList[position]
                // 弹框显示
                Toast.makeText(this@SimpleAdapterActivity, city.text, Toast.LENGTH_SHORT).show()
            }

            override fun onNothingSelected(p0: AdapterView<*>?) {
                TODO("Not yet implemented")
            }
        }

    }
}